package com.group.elmboot.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.group.elmboot.mapper.*;
import com.group.elmboot.po.*;
import com.group.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.group.elmboot.service.OrdersService;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private BusinessMapper businessMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
	@Autowired
	private FoodMapper foodMapper;
	@Autowired
	private WalletMapper walletMapper;

	@Override
	@Transactional
	public int createOrders(Orders orders) {
		//1、查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);
		
		//2、创建订单（返回生成的订单编号）
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();
		
		//3、批量添加订单明细
		List<OrderDetailet> list = new ArrayList<>();
		for(Cart c : cartList) {
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodId(c.getFoodId());
			od.setQuantity(c.getQuantity());
			Food food=foodMapper.getFoodById(c.getFoodId());
			od.setFoodName(food.getFoodName());
			od.setFoodPrice(food.getFoodPrice());
			list.add(od);
		}
		orderDetailetMapper.saveOrderDetailetBatch(list);
		
		//4、从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);
		
		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}
	
	@Override
	public List<Orders> listOrdersByBusinessId(Integer businessId){
		return ordersMapper.listOrdersByBusinessId(businessId);
	}
	
	@Override
	@Transactional
	public int payOrders(Orders orders,String redPacket) throws Exception {
		if(ordersMapper.getOrderStateById(orders.getOrderId())==1)
			return -1;
		ordersMapper.payOrders(orders.getOrderId());
		orders=ordersMapper.getOrdersById(orders.getOrderId());
		businessMapper.salesPlus(orders.getBusinessId());
		String managerId=businessMapper.getBusinessById(orders.getBusinessId()).getManager();
		Wallet managerWallet=walletMapper.selectById(managerId);
		managerWallet.increaseFrozenAmount(BigDecimal.valueOf(orders.getOrderTotal()).subtract(new BigDecimal(redPacket)));
		return orders.getOrderId();
	}
}
